//
//  WebIntegralViewController.m
//  sensen_ios
//
//  Created by mc on 16/4/15.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "WebIntegralViewController.h"
#import "NSString+Helper.h"


@interface WebIntegralViewController ()<UMSocialUIDelegate>
{
    UILabel *_loadLabel; // 网页加载提示文字
    UIActivityIndicatorView *_indicatorView; // 网页加载菊花转动
    NSString *_string;
    
}
@property (nonatomic, strong) UIView *shareView; // 分享视图


@end

@implementation WebIntegralViewController

// 自定义初始化方法，获取所要显示的网页的网址，并显示该网页
- (instancetype)initWithUrlString:(NSString *)urlString {
    self = [super init];
    if (self) {
        // 创建网页webView
        CGRect frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT -15- 50);
        _webView = [[UIWebView alloc] initWithFrame:frame];
        _webView.delegate = self;
        _webView.scalesPageToFit = YES;
        [self.view addSubview:_webView];
        self.view.backgroundColor = rgba(255, 255, 255, 1);
        
        
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:button];
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.bottom.equalTo(self.view).offset(0);
            make.left.equalTo(self.view).offset(0);
            make.right.equalTo(self.view).offset(0);
            make.height.mas_equalTo(@50);
        }];
        
        button.backgroundColor = SS_NAVI_ORANGE_COLOR;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitle:@"分享给好友" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
        
        
        
        _string = urlString;
        // 发送请求，获取该网页内容
        urlString = [urlString stringByEncodingURLFormat];
        
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        [_webView loadRequest:request];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
}



- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    
    //导航栏默认黄色
    if (!self.color) {
        self.color = SS_NAVI_ORANGE_COLOR;
    }
    // 设置背景颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:self.color] forBarMetrics:UIBarMetricsDefault];
    
    self.title =  self.titleString;
    // 进来的时候要隐藏导航栏
    MainTabBarController *tabBarController = (MainTabBarController *)self.navigationController.tabBarController;
    [tabBarController hideTabBar];
    
    //  创建导航栏左边返回按钮，此方法由父类实现
    [self createLeftBarButtonItemWithImagename:nil];
}
// 右侧按钮的样式可以自定义，由imgname控制，如果是文字则调用下面的接口
- (void)createRightBarButtonItemWithImagename:(NSString *)imgname {
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [rightButton addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setImage:[UIImage imageNamed:imgname] forState:UIControlStateNormal];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
}

#pragma mark - UIVebView代理方法
// 开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView {
    // 创建提示文字
    _loadLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    _loadLabel.text = @"加载中...";
    _loadLabel.textAlignment = NSTextAlignmentCenter;
    _loadLabel.textColor = [UIColor lightGrayColor];
    _loadLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:_loadLabel];
    
    // 加载网页时，菊花转动
    _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    CGPoint point = CGPointMake(self.view.width/4, -20);
    _indicatorView.center = point;
    [_loadLabel addSubview:_indicatorView];
    _indicatorView.hidesWhenStopped = YES;
    [_indicatorView startAnimating];
}

// 加载结束
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // 加载提示移除
    [_indicatorView stopAnimating];
    [_loadLabel removeFromSuperview];
    _loadLabel = nil;
}


#pragma mark - 返回上一界面
// 返回上一界面，覆写父类方法
- (void)leftAction:(UIButton *)button {
    if (_webView.canGoBack) {
        [_webView goBack];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}



- (void)rightAction:(UIButton *)button{
    
     [self showShareView];
    
    
//    NSString *shareText = @"森森分享有礼";
//    NSString *url = _string; // 要分享的网址
//    // 微信处理
//    [UMSocialWechatHandler setWXAppId:APPKEY_WEIXIN appSecret:APPSECRET_WEIXIN url:url];
//    [UMSocialQQHandler setQQWithAppId:APPID_QQ appKey:APPKEY_QQ url:url];
//    
//    
//    // TODO: 分享链接的问题®
//    // 微博分享的处理
//    [UMSocialData defaultData].extConfig.sinaData.shareText = shareText;
//    [UMSocialData defaultData].extConfig.sinaData.urlResource.url = url;
//    [UMSocialData defaultData].extConfig.sinaData.urlResource.resourceType = UMSocialUrlResourceTypeImage;
//    
//    // 微信消息类型
//    [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
//    
//    // 微信朋友圈分享
//    [UMSocialData defaultData].extConfig.wechatTimelineData.title = @"微信朋友圈分享title";
//    [UMSocialData defaultData].extConfig.wechatTimelineData.url = url;
//    
//    // 微信好友分享
//    [UMSocialData defaultData].extConfig.wechatSessionData.title = @"微信好友分享title";
//    [UMSocialData defaultData].extConfig.wechatSessionData.url = url;
//    
//    // qq分享
//    [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
//    [UMSocialData defaultData].extConfig.qqData.title = @"QQ分享title";
//    [UMSocialData defaultData].extConfig.qzoneData.title = @"QQ空间分享title";
//    [UMSocialData defaultData].extConfig.qqData.url = url;
//    [UMSocialData defaultData].extConfig.qzoneData.url = url;
//    
//    // 实现分享
//    [UMSocialSnsService presentSnsIconSheetView:self
//                                         appKey:APPKEY_UMENG_SOCIAL
//                                      shareText:shareText
//                                     shareImage:DEFAULTSHARE_IMAGE
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToQQ,UMShareToWechatSession,UMShareToWechatTimeline,nil]
//                                       delegate:self];
//    
//    
//    // 使用自定义分享列表面板，则在对应的（微信，qq，微博等）分享按钮中实现下面的方法
//    //    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession]
//    //                                                       content:@"分享内嵌文字"
//    //                                                         image:nil
//    //                                                      location:nil
//    //                                                   urlResource:nil
//    //                                           presentedController:self
//    //                                                    completion:^(UMSocialResponseEntity *response) {
//    //        if (response.responseCode == UMSResponseCodeSuccess) {
//    //            NSLog(@"分享成功！");
//    //        }
//    //    }];
    
    
}


- (UIView *)shareView {
    
    if (_shareView == nil) {
        _shareView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _shareView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        _shareView.alpha = 0;
        _shareView.hidden = YES;
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:_shareView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideShareView)];
        [_shareView addGestureRecognizer:tap];
        
        UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _shareView.width, 80)];
        contentView.backgroundColor = [UIColor whiteColor];
        [_shareView addSubview:contentView];
        contentView.top = _shareView.height;
        contentView.tag = 1000;
        
        NSArray *titles = @[@"QQ", @"微信", @"朋友圈"];
        NSArray *images = @[@"QQ分享", @"微信", @"朋友圈"];
        for (int i = 0; i < titles.count; i ++) {
            CGFloat x, y = 0, width = SCREEN_WIDTH / titles.count, height = contentView.height;
            x = i * width;
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(x, y, width, height);
            button.backgroundColor = [UIColor clearColor];
            [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
            [button setImage:[UIImage imageNamed:images[i]] forState:UIControlStateNormal];
            [button setImageEdgeInsets:UIEdgeInsetsMake(10, (button.width / 2 - 20), 30, (button.width / 2 - 20))];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = 2000 + i;
            [contentView addSubview:button];
            
            x = 0;
            y = 0;
            width = button.width;
            height = 20;
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
            label.font = FONT(12);
            label.text = titles[i];
            label.textColor = [UIColor darkGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [button addSubview:label];
            label.bottom = button.height - 10;
        }
        
    }
    
    return _shareView;
}
- (void)showShareView {
    self.shareView.hidden = NO;
    
    UIView *contentView = [self.shareView viewWithTag:1000];
    [UIView animateWithDuration:0.3 animations:^{
        _shareView.alpha = 1;
        contentView.bottom = self.shareView.height;
    }];
}
- (void)hideShareView {
    UIView *contentView = [self.shareView viewWithTag:1000];
    [UIView animateWithDuration:0.3 animations:^{
        self.shareView.alpha = 0;
        contentView.top = self.shareView.height;
    } completion:^(BOOL finished) {
        self.shareView.hidden = YES;
    }];
}
- (void)shareBtnAction:(UIButton *)button {
    
    [self hideShareView];
    
    NSString *shareText = @"森森分享有礼";
    NSString *url = _string; // 要分享的网址
    
    // 微信处理
    [UMSocialWechatHandler setWXAppId:APPKEY_WEIXIN appSecret:APPSECRET_WEIXIN url:url];
    [UMSocialQQHandler setQQWithAppId:APPID_QQ appKey:APPKEY_QQ url:url];
    // TODO: 分享链接的问题®
    // 微博分享的处理
    [UMSocialData defaultData].extConfig.sinaData.shareText = shareText;
    [UMSocialData defaultData].extConfig.sinaData.urlResource.url = url;
    [UMSocialData defaultData].extConfig.sinaData.urlResource.resourceType = UMSocialUrlResourceTypeImage;
    
    // 微信消息类型
    [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
    
    // 微信朋友圈分享
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = shareText;
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = url;
    
    // 微信好友分享
    [UMSocialData defaultData].extConfig.wechatSessionData.title = shareText;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = url;
    
    // qq分享
    [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
    [UMSocialData defaultData].extConfig.qqData.title = shareText;
    [UMSocialData defaultData].extConfig.qzoneData.title = shareText;
    [UMSocialData defaultData].extConfig.qqData.url = url;
    [UMSocialData defaultData].extConfig.qzoneData.url = url;
    
    UIImageView * imageView  = [[UIImageView alloc] init];
    
    switch (button.tag) {
        case 2000:
        {
            
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQQ]
                                                               content:shareText
                                                                 image:DEFAULTSHARE_IMAGE//[UIImage getImageFromURL:self.model.main_img]
                                                              location:nil
                                                           urlResource:nil
                                                   presentedController:self
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                if (response.responseCode == UMSResponseCodeSuccess) {
                                                                    NSLog(@"分享成功！");
                                                                }
                                                            }];
        }
            break;
        case 2001:
        {
           
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession]
                                                               content:shareText
                                                                 image:DEFAULTSHARE_IMAGE
                                                              location:nil
                                                           urlResource:nil
                                                   presentedController:self
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                if (response.responseCode == UMSResponseCodeSuccess) {
                                                                    NSLog(@"分享成功！");
                                                                }
                                                            }];
        }
            break;
        case 2002:
        {
           
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatTimeline]
                                                               content:shareText
                                                                 image:DEFAULTSHARE_IMAGE
                                                              location:nil
                                                           urlResource:nil
                                                   presentedController:self
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                if (response.responseCode == UMSResponseCodeSuccess) {
                                                                    NSLog(@"分享成功！");
                                                                }
                                                            }];
        }
            break;
            
        default:
            break;
    }
}










- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
